package com.bjpowernode.web.service;

import com.alibaba.fastjson.JSONObject;
import com.bjpowernode.common.P2PKey;
import com.bjpowernode.web.config.JdSmsConfig;
import javafx.util.Builder;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.lang.annotation.Documented;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;


@Service
public class SmsService {

    @Resource
    private JdSmsConfig jdSmsConfig;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 发送短信
     * 返回值：表示生成的短信验证码的内容
     */

    public String sendSms(String phone){

        String codeResult ="";
        String code= makeCode(4);//4位数的验证码

        //【凯信通】您的验证码是：%s(占位符)
        String smsContext= String.format(jdSmsConfig.getContent(),code );

        StringBuilder url =new StringBuilder("");
        url.append(jdSmsConfig.getUrl()).append("?mobile=").append(phone)
                .append("&content=").append(smsContext)
                .append("&appKey=").append(jdSmsConfig.getAppkey());

        System.out.println("url====="+url);


        try {
            CloseableHttpClient client= HttpClients.createDefault();
            HttpGet get =new HttpGet(url.toString());
            CloseableHttpResponse response =client.execute(get);
            if (response.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
                //String result = EntityUtils.toString(response.getEntity());

                //模拟使用的数据
                String result="{\n" +
                        "    \"code\": \"10000\",\n" +
                        "    \"charge\": false,\n" +
                        "    \"remain\": 0,\n" +
                        "    \"msg\": \"查询成功\",\n" +
                        "    \"result\": \"<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\" ?><returnsms>\\n <returnstatus>Success</returnstatus>\\n <message>ok</message>\\n <remainpoint>-1111611</remainpoint>\\n <taskID>101609164</taskID>\\n <successCounts>1</successCounts></returnsms>\"\n" +
                        "}";
                if (!"".equals(result)) {
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    if (jsonObject != null && "10000".equals(jsonObject.getString("code"))) {
                        String xml = jsonObject.getString("result");
                        //使用dom4j处理xml数据
                        String statusValue = queryXmlNodeValue(xml);
                        if ("Success".equalsIgnoreCase(statusValue)){
                            //发送短信成功
                            //存到redis,设置时间为5分钟
                            ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
                            valueOperations.set(P2PKey.REGISTER_SMS_CODE+phone,code,10, TimeUnit.MINUTES);
                            codeResult=code;
                        }else {
                            codeResult ="error";//发送失败
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return codeResult;
    }


    //生成自定义位数的验证码
    private String makeCode(int len){
        StringBuilder Builder =new StringBuilder("");
        ThreadLocalRandom  random=ThreadLocalRandom.current();
        for (int i = 0; i < len; i++) {
            Builder.append(random.nextInt(10));//10以内
        }
        return Builder.toString();
    }

    //处理xml
    private String queryXmlNodeValue(String xml){
        String result="";
        try {
            Document document= DocumentHelper.parseText(xml);
            Node node=document.selectSingleNode("//returnstatus");
            if (node!=null){
                result=node.getStringValue();
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 对比请求中的验证码和redis中的验证码
     * @param smsCode
     * @return
     */

    public boolean checkSmsCode(String phone,String smsCode){
        boolean result=false;
        String dbCode=stringRedisTemplate.opsForValue().get((P2PKey.REGISTER_SMS_CODE+phone));
        if (smsCode.equals(dbCode)){
            result=true;
        }
        return result;
    }
}
